package org.gridgain.internal.h2.vector;

import java.util.ArrayList;
import java.util.List;

public class MyUtil {

    public static Object[] parentPage(MyPage p, Object key)
    {
        while (true)
        {
            int index = p.binarySearch(key);
            if (p.isLeaf())
            {
                return null;
            }
            else if (index++ < 0) {
                index = -index;
            }
            MyPage p1 = p.queryChildPage(p, index);

            if (p1 != null && p1.isLeaf())
            {
                return new Object[] {p, index};
            }
            p = p1;
        }
    }

    public static MyPage leftPage(MyPage p, Object key)
    {
        if (key != null) {
            Object[] bs = parentPage(p, key);
            if (bs != null) {
                if ((int) bs[1] - 1 >= 0) {
                    MyPage p1 = MyPage.queryChildPage((MyPage) bs[0], (int) bs[1] - 1);
                    return p1;
                }
            }
        }
        return null;
    }

    public static MyPage rightPage(MyPage p, Object key)
    {
        if (key != null) {
            Object[] bs = parentPage(p, key);
            if (bs != null) {
                MyPage ppage = (MyPage) bs[0];
                int pindex = (int) bs[1];
                if (ppage.children.length > pindex + 1) {
                    MyPage p1 = MyPage.queryChildPage(ppage, pindex + 1);
                    return p1;
                }
            }
        }
        return null;
    }

    public static Object[] query(MyPage p, Object key)
    {
        if (key != null) {
            Object[] lst;
            Object fkey = null;
            while (true) {
                Object[] objs = p.queryKey(fkey, key);
                int index = (int) objs[0];
                if (p.isLeaf()) {
                    if (index >= 0) {
                        //lst.add(p.getValue(index));
                        lst = new Object[]{p, index};
                    } else {
                        //lst.add(p.getValue(p.keys.length - 1));
                        lst = new Object[]{p, p.keys.length - 1};
                    }
                    return lst;
                    //return index >= 0 ? p.getValue(index) : null;
                } else if (index++ < 0) {
                    index = -index;
                }
                fkey = objs[1];
                p = p.queryChildPage(p, index);
            }
        }
        return null;
    }

    public static Double[] getDs(Double[] value)
    {
        List<Double> lst = new ArrayList<>();
        for (int i = 0; i < value.length; i++)
        {
            lst.add(0D);
        }

        return lst.toArray(new Double[0]);
    }

    public static Double[] getDsCos(Double[] value)
    {
        List<Double> lst = new ArrayList<>();
        for (int i = 0; i < value.length; i++)
        {
            lst.add(1D);
        }

        return lst.toArray(new Double[0]);
    }
}
